import {createOrder, getProductDetail, queryOrderStatus} from "@src/api/points";
import router from "@src/router";
import base from "@src/store/base";
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'

Component({
  behaviors: [router.routerBehavior, storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }],
  properties: {
    productNo: {
      type: String,
      value: ""
    }
  },
  data: {
    productDetailData: null,
    queryNum: 0,
    orderNo: null,
    timeoutId: null,
    statusMap: {
      1: '立即兑换',
      2: '商品已下架',
      3: '兑换完了',
      4: '非兑换时间',
      5: '商品过期',
    }
  },
  methods: {
    onLogin() {
      this.productDetailReq()
    },
    onUnload() {
      if (this.data.timeoutId) {
        clearTimeout(this.data.timeoutId)
      }
    },
    onShareAppMessage(res) {
      return {
        title: `分享好礼给你，只需 ${this.data.productDetailData.productPoint} 积分即可兑换，快来一起兑换吧`,
        path: `sp-member/pages/redemptionDetails/main?productNo=${this.data.productNo}`,
        desc: "",
        imageUrl: this.data.shareImg
      };
    },
    productDetailReq() {
      getProductDetail({productNo: this.data.productNo}).then(res => {
        if (res.code === 0) {
          let descriptionArr = res.data.description.split(/[(\r\n)\n]+/);
          this.setData({productDetailData: res.data, descriptionArr: descriptionArr})
        }
      })
    },
    createOrderReq() {
      // 兑换商品
      let data = {num: 1, productNo: this.data.productNo};
      return createOrder(data).then(res => {
        if (res.code === 0) {
          let {orderNo, code} = res.data;
          if (code === 0) {
            this.setData({orderNo: orderNo, queryNum: 1})
            this.queryStatusReq(orderNo);
          } else {
            // 异常
            this.buyError({reason: res.data.reason})
          }
        }
      })
    },
    queryStatusReq() {
      let data = {
        orderNo: this.data.orderNo
      };
      wx.showLoading({title: "订单结果查询中...", mask: true});
      queryOrderStatus(data).then(res => {
        if (res.code === 0) {
          let {status} = res.data;
          if (status === 0) {
            if (this.data.queryNum < 30) {
              this.setData({queryNum: this.data.queryNum + 1})
              let timeoutId = setTimeout(() => {
                this.queryStatusReq()
              }, 500)
              this.setData({timeoutId: timeoutId})
              return;
            } else {
              this.buyError({reason: "查询订单状态过多,服务器处理异常"})
            }
          }

          if (status === 1) {
            wx.hideLoading()
            this.buySuccess();
          } else {
            wx.hideLoading()
            this.buyError({reason: res.data.reason});
          }
          this.setData({timeoutId: null})
        }
      }).catch(() => {
        wx.hideLoading()
      })
    },
    buySuccess() {
      this.productDetailReq();
      wx.showModal({
        title: "提示",
        content: "兑换成功",
        cancelText: "继续兑换",
        confirmText: "兑换详情",
        success: (res) => {
          if (res.confirm) {
            router.push({name: 'member/redemptionRecordDetails', params: {orderNo: this.data.orderNo}})
          }
        }
      });
    },
    buyError(result) {
      wx.showToast({
        title: result.reason ? result.reason: "积分不足, 兑换失败",
        icon: "none",
        duration: 4000
      });
    },

    // 兑换按钮
    showBuyDialog() {
      if (this.data.productDetailData.productState === 1) {
        this.setData({redemptionModal: true})
      }
    },
    handleCancel() {
      this.setData({redemptionModal: false})
    },
    // 确认兑换
    handleConfirmRedemptionBtn() {
      wx.showLoading({title: "下单中...", mask: true});
      this.setData({redemptionModal: false})
      this.createOrderReq();
    },
    handleGenPoster(e) {
      this.setData({"shareImg": e.detail})
    }
  }
})
